<template>
  <div class="task-management" v-loading="loading">
    <!-- 工具栏 -->
    <div class="task-toolbar">
      <div class="toolbar-left">
        <h3 class="task-title">{{ $t('project.taskManagement') }}</h3>
        <div class="task-filters">
          <!-- 项目选择 -->
          <el-select 
            v-model="selectedProjectId" 
            :placeholder="$t('project.selectProject')"
            class="project-select"
            @change="handleProjectChange"
          >
            <el-option
              v-for="project in projects"
              :key="project.id"
              :label="project.name"
              :value="project.id"
            />
          </el-select>
          
          <!-- 状态筛选 -->
          <el-select 
            v-model="selectedStatus" 
            :placeholder="$t('project.allStatus')"
            class="status-select"
            clearable
            @change="handleStatusChange"
          >
            <el-option
              v-for="status in statusOptions"
              :key="status.value"
              :label="status.label"
              :value="status.value"
            />
          </el-select>

          <!-- 分配者筛选 -->
          <el-select 
            v-model="selectedAssignee" 
            :placeholder="$t('project.allAssignees')"
            class="assignee-select"
            clearable
            filterable
            @change="handleAssigneeChange"
          >
            <el-option
              v-for="member in teamMembers"
              :key="member.userId"
              :label="member.username || member.nickname || `用户${member.userId}`"
              :value="member.userId"
            >
              <div class="member-option">
                <el-avatar :size="20" :src="member.avatarUrl">
                  {{ (member.username || member.nickname || 'U')?.charAt(0).toUpperCase() }}
                </el-avatar>
                <span>{{ member.username || member.nickname || `用户${member.userId}` }}</span>
              </div>
            </el-option>
          </el-select>
        </div>
      </div>
      
      <div class="toolbar-right">
        <el-input
          v-model="searchKeyword"
          :placeholder="$t('project.searchTasks')"
          :prefix-icon="Search"
          class="search-input"
          @input="handleSearch"
          clearable
        />
        <el-button 
          v-if="canManage && selectedProjectId"
          type="primary" 
          :icon="Plus"
          @click="showCreateDialog = true"
        >
          {{ $t('project.createTask') }}
        </el-button>
        <el-button :icon="Refresh" @click="fetchTasks">
          {{ $t('common.refresh') }}
        </el-button>
      </div>
    </div>

    <!-- 任务统计卡片 -->
    <div class="task-stats" v-if="selectedProjectId && taskStats">
      <el-row :gutter="16">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-value">{{ taskStats.totalTasks }}</div>
              <div class="stat-label">{{ $t('project.totalTasks') }}</div>
            </div>
            <el-icon class="stat-icon total"><Document /></el-icon>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card todo">
            <div class="stat-content">
              <div class="stat-value">{{ taskStats.todoTasks }}</div>
              <div class="stat-label">{{ $t('project.todoTasks') }}</div>
            </div>
            <el-icon class="stat-icon"><Clock /></el-icon>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card progress">
            <div class="stat-content">
              <div class="stat-value">{{ taskStats.inProgressTasks }}</div>
              <div class="stat-label">{{ $t('project.inProgressTasks') }}</div>
            </div>
            <el-icon class="stat-icon"><VideoPlay /></el-icon>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card completed">
            <div class="stat-content">
              <div class="stat-value">{{ taskStats.completedTasks }}</div>
              <div class="stat-label">{{ $t('project.completedTasks') }}</div>
            </div>
            <el-icon class="stat-icon"><CircleCheck /></el-icon>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 任务列表 -->
    <div class="task-list-container">
      <el-card v-if="!selectedProjectId" class="empty-state">
        <el-empty 
          :description="$t('project.selectProjectFirst')" 
          :image-size="120"
        >
          <template #image>
            <el-icon size="120"><FolderOpened /></el-icon>
          </template>
        </el-empty>
      </el-card>

      <div v-else-if="tasks.length === 0" class="empty-tasks">
        <el-empty 
          :description="$t('project.noTasks')" 
          :image-size="100"
        >
          <el-button 
            v-if="canManage"
            type="primary" 
            @click="showCreateDialog = true"
          >
            {{ $t('project.createFirstTask') }}
          </el-button>
        </el-empty>
      </div>

      <div v-else class="task-list">
        <TaskCard
          v-for="task in tasks"
          :key="task.id"
          :task="task"
          :can-manage="canManage"
          :team-members="teamMembers"
          @edit="handleEditTask"
          @delete="handleDeleteTask"
          @status-change="handleTaskStatusChange"
          @assign="handleAssignTask"
        />
      </div>

      <!-- 分页 -->
      <div class="pagination-container" v-if="tasks.length > 0">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 创建任务对话框 -->
    <CreateTaskDialog
      v-model="showCreateDialog"
      :project-id="selectedProjectId"
      :team-members="teamMembers"
      @success="handleCreateSuccess"
    />

    <!-- 编辑任务对话框 -->
    <EditTaskDialog
      v-model="showEditDialog"
      :task="selectedTask"
      :team-members="teamMembers"
      @success="handleEditSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Refresh,
  Search,
  Document,
  Clock,
  VideoPlay,
  CircleCheck,
  FolderOpened
} from '@element-plus/icons-vue'
import { projectApi, taskApi } from '@/api/project'
import { useTeamStore } from '@/stores/teamStore'
import type { Project, Task, TaskStatistics } from '@/types/project'
import { TaskStatus } from '@/types/project'
import TaskCard from './TaskCard.vue'
import CreateTaskDialog from './CreateTaskDialog.vue'
import EditTaskDialog from './EditTaskDialog.vue'

// Props
interface Props {
  teamId: number
  canManage: boolean
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  taskUpdated: []
}>()

const { t } = useI18n()
const teamStore = useTeamStore()

// 响应式数据
const loading = ref(false)
const projects = ref<Project[]>([])
const tasks = ref<Task[]>([])
const taskStats = ref<TaskStatistics | null>(null)
const selectedProjectId = ref<number | null>(null)
const selectedStatus = ref<string>('')
const selectedAssignee = ref<number | null>(null)
const searchKeyword = ref('')
const showCreateDialog = ref(false)
const showEditDialog = ref(false)
const selectedTask = ref<Task | null>(null)

// 分页数据
const pagination = ref({
  page: 1,
  size: 20,
  total: 0
})

// 计算属性
const teamMembers = computed(() => {
  return teamStore.teamMembers.filter(member => member.status === 'ACTIVE')
})

const statusOptions = computed(() => [
  { value: TaskStatus.TODO, label: t('project.status.todo') },
  { value: TaskStatus.IN_PROGRESS, label: t('project.status.inProgress') },
  { value: TaskStatus.REVIEW, label: t('project.status.review') },
  { value: TaskStatus.COMPLETED, label: t('project.status.completed') },
  { value: TaskStatus.CANCELLED, label: t('project.status.cancelled') }
])

// 方法
const fetchProjects = async () => {
  try {
    const response = await projectApi.getTeamProjects(props.teamId)

    if (response.code !== 200) {
      throw new Error(response.message || '获取项目列表失败')
    }

    projects.value = response.data || []

    // 如果有项目且没有选中项目，默认选中第一个
    if (projects.value.length > 0 && !selectedProjectId.value) {
      selectedProjectId.value = projects.value[0].id
      await fetchTasks()
      await fetchTaskStats()
    }
  } catch (error: any) {
    console.error('获取项目列表失败:', error)
    ElMessage.error(error.message || t('project.fetchError'))
  }
}

const fetchTasks = async () => {
  if (!selectedProjectId.value) return

  try {
    loading.value = true

    let response
    if (searchKeyword.value) {
      // 搜索任务
      response = await taskApi.searchTasks(selectedProjectId.value, searchKeyword.value)

      if (response.code !== 200) {
        throw new Error(response.message || '搜索任务失败')
      }

      tasks.value = response.data || []
      pagination.value.total = tasks.value.length
    } else {
      // 分页获取任务
      response = await taskApi.getProjectTasksPage(
        selectedProjectId.value,
        {
          page: pagination.value.page - 1, // 后端从0开始
          size: pagination.value.size
        },
        selectedStatus.value || undefined
      )

      if (response.code !== 200) {
        throw new Error(response.message || '获取任务列表失败')
      }

      tasks.value = response.data?.content || []
      pagination.value.total = response.data?.totalElements || 0
    }

    // 如果有分配者筛选，前端过滤
    if (selectedAssignee.value) {
      tasks.value = tasks.value.filter(task => task.assigneeId === selectedAssignee.value)
    }
  } catch (error: any) {
    console.error('获取任务列表失败:', error)
    ElMessage.error(error.message || t('project.fetchTasksError'))
  } finally {
    loading.value = false
  }
}

const fetchTaskStats = async () => {
  if (!selectedProjectId.value) return

  try {
    const response = await taskApi.getTaskStatistics(selectedProjectId.value)

    if (response.code !== 200) {
      throw new Error(response.message || '获取任务统计失败')
    }

    taskStats.value = response.data
  } catch (error: any) {
    console.error('获取任务统计失败:', error)
    // 统计失败不显示错误消息，只在控制台记录
  }
}

const handleProjectChange = async () => {
  pagination.value.page = 1
  selectedStatus.value = ''
  selectedAssignee.value = null
  searchKeyword.value = ''
  await fetchTasks()
  await fetchTaskStats()
}

const handleStatusChange = async () => {
  pagination.value.page = 1
  await fetchTasks()
}

const handleAssigneeChange = async () => {
  pagination.value.page = 1
  await fetchTasks()
}

const handleSearch = async () => {
  pagination.value.page = 1
  await fetchTasks()
}

const handleSizeChange = async (size: number) => {
  pagination.value.size = size
  pagination.value.page = 1
  await fetchTasks()
}

const handleCurrentChange = async (page: number) => {
  pagination.value.page = page
  await fetchTasks()
}

const handleCreateSuccess = () => {
  showCreateDialog.value = false
  fetchTasks()
  fetchTaskStats()
  emit('taskUpdated')
}

const handleEditTask = (task: Task) => {
  selectedTask.value = task
  showEditDialog.value = true
}

const handleEditSuccess = () => {
  showEditDialog.value = false
  selectedTask.value = null
  fetchTasks()
  fetchTaskStats()
  emit('taskUpdated')
}

const handleDeleteTask = async (task: Task) => {
  try {
    await ElMessageBox.confirm(
      t('project.deleteTaskConfirmMessage', { title: task.title }),
      t('project.deleteTaskConfirmTitle'),
      {
        confirmButtonText: t('common.confirm'),
        cancelButtonText: t('common.cancel'),
        type: 'warning'
      }
    )

    await taskApi.deleteTask(task.id)
    ElMessage.success(t('project.deleteTaskSuccess'))
    fetchTasks()
    fetchTaskStats()
    emit('taskUpdated')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除任务失败:', error)
      ElMessage.error(t('project.deleteTaskError'))
    }
  }
}

const handleTaskStatusChange = async (task: Task, newStatus: string) => {
  try {
    await taskApi.updateTaskStatus(task.id, newStatus)
    task.status = newStatus
    ElMessage.success(t('project.taskStatusUpdateSuccess'))
    fetchTaskStats()
    emit('taskUpdated')
  } catch (error) {
    console.error('更新任务状态失败:', error)
    ElMessage.error(t('project.taskStatusUpdateError'))
  }
}

const handleAssignTask = async (task: Task, assigneeId: number) => {
  try {
    await taskApi.assignTask(task.id, assigneeId)
    task.assigneeId = assigneeId
    ElMessage.success(t('project.taskAssignSuccess'))
    emit('taskUpdated')
  } catch (error) {
    console.error('分配任务失败:', error)
    ElMessage.error(t('project.taskAssignError'))
  }
}

// 生命周期
onMounted(() => {
  fetchProjects()
  
  // 加载团队成员
  if (teamStore.teamMembers.length === 0) {
    teamStore.fetchTeamMembers(props.teamId)
  }
})

// 监听teamId变化
watch(() => props.teamId, () => {
  if (props.teamId) {
    fetchProjects()
  }
})
</script>

<style scoped lang="scss">
.task-management {
  .task-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 24px;
    gap: 24px;

    .toolbar-left {
      flex: 1;

      .task-title {
        margin: 0 0 16px 0;
        font-size: 20px;
        font-weight: 600;
        color: var(--el-text-color-primary);
      }

      .task-filters {
        display: flex;
        gap: 12px;
        flex-wrap: wrap;

        .project-select {
          min-width: 200px;
        }

        .status-select,
        .assignee-select {
          min-width: 150px;
        }
      }
    }

    .toolbar-right {
      display: flex;
      gap: 12px;
      align-items: center;

      .search-input {
        width: 250px;
      }
    }
  }

  .task-stats {
    margin-bottom: 24px;

    .stat-card {
      position: relative;
      overflow: hidden;

      .stat-content {
        .stat-value {
          font-size: 24px;
          font-weight: 600;
          color: var(--el-text-color-primary);
          margin-bottom: 4px;
        }

        .stat-label {
          font-size: 14px;
          color: var(--el-text-color-secondary);
        }
      }

      .stat-icon {
        position: absolute;
        right: 16px;
        top: 50%;
        transform: translateY(-50%);
        font-size: 32px;
        opacity: 0.3;

        &.total {
          color: var(--el-color-info);
        }
      }

      &.todo .stat-icon {
        color: var(--el-color-warning);
      }

      &.progress .stat-icon {
        color: var(--el-color-primary);
      }

      &.completed .stat-icon {
        color: var(--el-color-success);
      }
    }
  }

  .task-list-container {
    .empty-state,
    .empty-tasks {
      text-align: center;
      padding: 40px;
    }

    .task-list {
      display: grid;
      gap: 16px;
    }

    .pagination-container {
      margin-top: 24px;
      display: flex;
      justify-content: center;
    }
  }
}

.member-option {
  display: flex;
  align-items: center;
  gap: 8px;
}

// 响应式设计
@media (max-width: 1200px) {
  .task-management {
    .task-toolbar {
      flex-direction: column;
      align-items: stretch;

      .toolbar-left {
        .task-filters {
          .project-select,
          .status-select,
          .assignee-select {
            min-width: 120px;
          }
        }
      }

      .toolbar-right {
        justify-content: flex-end;

        .search-input {
          width: 200px;
        }
      }
    }

    .task-stats {
      .el-row {
        .el-col {
          margin-bottom: 16px;
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .task-management {
    .task-toolbar {
      .toolbar-left {
        .task-filters {
          flex-direction: column;

          .project-select,
          .status-select,
          .assignee-select {
            width: 100%;
          }
        }
      }

      .toolbar-right {
        flex-direction: column;
        align-items: stretch;

        .search-input {
          width: 100%;
        }
      }
    }
  }
}
</style>
